package com.example.atuserdemo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.Editable.Factory;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

public class AtUserEditText extends EditText {

	private String userId = null;
	private String mNickName;
	private int nameLength;
	private Context mContext;

	public AtUserEditText(Context context) {
		this(context, null);
	}

	public AtUserEditText(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		this.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				Log.v("keyCode", keyCode + "");
				// 在这个区间什么都不让插入
				if (getSelectionStart() <= nameLength && keyCode != KeyEvent.KEYCODE_DEL) {
					AtUserEditText.this.setEditableFactory(new Factory() {

					});
				}
				if (keyCode == KeyEvent.KEYCODE_DEL) {
					int currPos = getSelectionStart();
					if (mNickName != null && currPos <= nameLength) {
						String orinalString = getTextWithoutAt();
						if (orinalString == null || orinalString.equals("")) {
							Log.v("is null", "is null");
						}
						setText(orinalString);
						mNickName = null;
						userId = null;
						nameLength = 0;
						return true;
					} else {
						return false;
					}
				}
				return false;
			}
		});

	}

	public String getUserId() {
		return userId;
	}

	@SuppressWarnings("deprecation")
	public void insertUser(String userId, String nickName) {
		if (this.userId == null && mNickName == null) {
			this.userId = userId;
			mNickName = "回复 @" + nickName + " ";
			nameLength = mNickName.length();
			this.setText(mNickName + this.getText());
			// 改变文字颜色
			SpannableString ss = new SpannableString(getText().toString());
			ss.setSpan(
					new ForegroundColorSpan(mContext.getResources().getColor(R.color.app_main_theme_color_not_clicked)),
					0, nameLength, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
			this.setText(ss);
			Editable editable = this.getText();
			Selection.setSelection(editable, nameLength);
		} else {
			String oldText = this.getText().toString().substring(mNickName.length(), getText().toString().length());

			this.userId = userId;
			mNickName = "回复 @" + nickName + " ";
			nameLength = mNickName.length();
			this.setText(mNickName + oldText);

			// 替换为图片
			SpannableString ss = new SpannableString(getText().toString());
			ss.setSpan(
					new ForegroundColorSpan(mContext.getResources().getColor(R.color.app_main_theme_color_not_clicked)),
					0, nameLength, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
			this.setText(ss);
			// 将光标移动到最后一位
			Editable editable = this.getText();
			Selection.setSelection(editable, nameLength);
		}
		
		this.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_UP) {
					Log.v("currentPos", getSelectionStart() + "");
				}
				return false;
			}
		});
	}

	public String getTextWithoutAt() {
		if (mNickName == null || nameLength == 0) {
			return getText().toString();
		} else {
			String orignalText = this.getText().toString().substring(mNickName.length(), getText().toString().length());
			return orignalText;
		}
	}

	/**
	 * 按照字符串返回图片
	 * 
	 * @param name
	 * @return
	 */
	private Bitmap getNameBitmap(String name) {
		name = "" + name;
		Paint paint = new Paint();
		paint.setColor(getResources().getColor(R.color.app_main_theme_color));
		paint.setAntiAlias(true);
		paint.setTextSize(30);
		Rect rect = new Rect();

		paint.getTextBounds(name, 0, name.length(), rect);

		int width = (int) (paint.measureText(name));

		final Bitmap bmp = Bitmap.createBitmap(width, rect.height(), Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(bmp);

		canvas.drawText(name, rect.left, rect.height() - rect.bottom, paint);

		File f = new File("/storage/sdcard1/name_pic.jpg");
		if (f.exists()) {
			f.delete();
		} else {
			try {
				FileOutputStream out = new FileOutputStream(f);
				bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
				out.flush();
				out.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return bmp;
	}
}
